package com.larry.yarn;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;

import java.io.IOException;

/**
 * @ProjectName YarnDemo
 * @Author larry
 * @Date 14:16 2021/11/10
 * @Description TODO
 **/
public class WordCount implements Tool {

    private Configuration conf;

    //核心驱动
    @Override
    public int run(String[] strings) throws Exception {
        Job job = Job.getInstance();
        job.setJarByClass(WordCountDriver.class);
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job,new Path(strings[0]));
        FileOutputFormat.setOutputPath(job,new Path(strings[1]));

        return job.waitForCompletion(true) ? 0 : 1;
    }

    /**
     *
     * @param configuration
     */
    @Override
    public void setConf(Configuration configuration) {
        this.conf = configuration;
    }

    /**
     *
     * @return
     */
    @Override
    public Configuration getConf() {
        return conf;
    }

    public class WordCountMapper extends Mapper<LongWritable, Text,Text, IntWritable>{
        private Text outK = new Text();
        private IntWritable outV = new IntWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split("\t");
            for (String s : split) {

                outK.set(s);

                context.write(outK,outV);
            }
        }
    }

    public class WordCountReducer extends Reducer<Text,IntWritable,Text,IntWritable>{

        private IntWritable outV = new IntWritable();
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }

            outV.set(sum);
            context.write(key,outV);
        }
    }
}
